<template>
    <n-form ref="formRef" class="select-none" :model="formData" :rules="rules">
        <n-form-item label="账号" path="account">
            <n-input
                v-model:value="formData.account"
                :disabled="model === 'update'"
                maxlength="9"
            />
        </n-form-item>
        <n-form-item label="用户名" path="username">
            <n-input v-model:value="formData.username" maxlength="15" />
        </n-form-item>
        <n-form-item v-if="model === 'create'" label="密码" path="password">
            <n-input v-model:value="formData.password" maxlength="15" />
        </n-form-item>
        <n-form-item v-if="model === 'update'" label="密码" path="password">
            <div class="w-full flex gap-10px">
                <n-input
                    disabled
                    default-value="12345678"
                    type="password"
                    class="w-full"
                />
                <n-button :focusable="false" @click="handleResetPassword">
                    修改密码
                </n-button>
            </div>
        </n-form-item>
        <div v-if="role === 'customer'">
            <n-form-item label="手机号" path="phone">
                <n-input
                    v-model:value="(formData as Customer).phone"
                    maxlength="11"
                />
            </n-form-item>
            <n-form-item label="公司名称" path="companyName">
                <n-input
                    v-model:value="(formData as Customer).companyName"
                    maxlength="20"
                    show-count
                />
            </n-form-item>
        </div>
        <template v-if="model === 'update' && !isUser">
            <n-form-item label="冻结" label-placement="left" path="frozen">
                <n-switch v-model:value="formData.frozen" />
            </n-form-item>
        </template>
    </n-form>
    <div class="w-full flex justify-end gap-10px">
        <n-button
            text
            v-if="model === 'create'"
            :focusable="false"
            @click="generateUser"
        >
            <n-icon :component="ReloadOutline" :size="18" />
        </n-button>
        <n-button ghost :focusable="false" @click="handleResetForm">
            重置
        </n-button>
        <n-button type="primary" :focusable="false" @click="handleSubmitForm">
            {{ model === "create" ? "新增" : "编辑" }}
        </n-button>
    </div>
</template>

<script lang="ts" setup>
import { h, ref, reactive, onMounted } from "vue";
import { NInput } from "naive-ui";
import type { FormInst, FormRules } from "naive-ui";
import type { Customer, User } from "@/service/api/types/user";
import { ReloadOutline } from "@vicons/ionicons5";

import _ from "lodash";

const props = defineProps<{
    role: "admin" | "customer" | "staff";
    data: User | Customer | null;
    model: "create" | "update";
    isUser?: boolean;
}>();

const emit = defineEmits<{
    (e: "submit:data", data: User | Customer): void;
    (e: "update:password", password: string): void;
}>();

const formRef = ref<FormInst | null>(null);

// 初始化用户数据
const emptyUser: User = {
    account: "",
    username: "",
    password: "",
    frozen: false,
    role: props.role,
    createdDate: 0,
};
// 初始化客户数据
const emptyCustomer: Customer = {
    account: "",
    username: "",
    password: "",
    phone: "",
    companyName: "",
    frozen: false,
    role: props.role,
    createdDate: 0,
};

const formData = reactive<User | Customer>({ ...emptyUser });

// 绑定修改密码时的新密码
const newPassword = ref<string>("");

const rules = reactive<FormRules>({
    account: [
        {
            required: true,
            validator: (_, value: string) => {
                if (value.length !== 9) {
                    return new Error("请输入9位账号");
                }
                return true;
            },
            trigger: ["input", "blur"],
        },
    ],
    username: [
        {
            required: true,
            validator: (_, value: string) => {
                if (value.length < 2) {
                    return new Error("请输入至少2位用户名");
                }
                return true;
            },
            trigger: ["input", "blur"],
        },
    ],
    password: [
        {
            required: props.model === "create" ? true : false,
            validator: (_, value: string) => {
                if (props.model === "update") {
                    return true;
                }
                if (value.length < 8) {
                    return new Error("请输入至少8位密码");
                }
                return true;
            },
            trigger: ["input", "blur"],
        },
    ],
    phone: [
        {
            required: true,
            validator: (_, value: string) => {
                if (!/^(?:(?:\+|00)86)?1[3-9]\d{9}$/.test(value)) {
                    return new Error("请输入11位手机号");
                }
                return true;
            },
            trigger: ["input", "blur"],
        },
    ],
    companyName: [
        {
            required: true,
            validator: (_, value: string) => {
                if (value.length === 0) {
                    return new Error("请输入公司名称");
                }
                return true;
            },
            trigger: ["input", "blur"],
        },
    ],
});

onMounted(() => {
    if (props.data) {
        Object.assign(formData, _.cloneDeep(props.data));
    } else {
        const data =
            props.role === "customer"
                ? _.cloneDeep(emptyCustomer)
                : _.cloneDeep(emptyUser);
        Object.assign(formData, data);
    }
});

// 生成用户数据
const generateUser = () => {
    if (props.role === "customer") {
        const customer: Customer = {
            account: _.random(100000000, 999999999).toString(),
            username: `测试客户${_.random(1000, 9999)}`,
            password: "12345678",
            phone: _.random(13000000000, 18999999999).toString(),
            companyName: `测试公司${_.random(1000, 9999)}`,
            frozen: false,
            role: "customer",
            createdDate: Date.now(),
        };
        Object.assign(formData, _.cloneDeep(customer));
    } else {
        const user: User = {
            account: _.random(100000000, 999999999).toString(),
            username: `员工${_.random(1000, 9999)}`,
            password: "12345678",
            frozen: false,
            role: "staff",
            createdDate: Date.now(),
        };
        Object.assign(formData, _.cloneDeep(user));
    }
};

const handleResetForm = () => {
    if (props.data) {
        Object.assign(formData, _.cloneDeep(props.data));
    } else {
        const data =
            props.role === "customer"
                ? _.cloneDeep(emptyCustomer)
                : _.cloneDeep(emptyUser);
        Object.assign(formData, data);
    }
    formRef.value?.restoreValidation();
};

const handleResetPassword = () => {
    window.NDialog.info({
        title: "修改密码",
        content: () => {
            return h(
                "div",
                {
                    class: "wh-100%",
                },
                [
                    h(NInput, {
                        value: newPassword.value,
                        onInput: (newValue: string) => {
                            newPassword.value = newValue;
                        },
                        type: "password",
                        class: "w-full",
                        showCount: true,
                        maxlength: 15,
                        placeholder: "请输入新的密码",
                    }),
                ]
            );
        },
        closable: false,
        positiveText: "确定",
        negativeText: "取消",
        onPositiveClick: async () => {
            if (newPassword.value.length < 8) {
                window.NMessage.error("请输入至少8位密码");
                return false;
            }
            formData.password = newPassword.value;
            emit("update:password", newPassword.value);
        },
    });
};

const handleSubmitForm = async () => {
    try {
        await formRef.value?.validate();
        if (_.isEqual(formData, props.data)) {
            window.NMessage.warning("没有修改任何内容");
            return;
        }
        if (formData.createdDate === 0) {
            formData.createdDate = Date.now();
        }
        console.log(formData);
        emit("submit:data", formData);
    } catch (error) {
        window.NMessage.error((error as Error).message || "请完成表单");
    }
};
</script>

<style scoped></style>
